package org.ricks.net.action.rpc;

import org.ricks.net.MessageProcessor;
import org.ricks.net.StateMachineEnum;
import org.ricks.net.action.ActionBus;
import org.ricks.net.action.context.FlowContext;
import org.ricks.net.action.context.head.RpcHeadMeta;
import org.ricks.net.action.utils.RpcException;
import org.ricks.net.transport.AioSession;
import java.io.IOException;
import java.nio.ByteBuffer;

public class RpcProcessor implements MessageProcessor<FlowContext<RpcHeadMeta>> {
    @Override
    public void process(AioSession session, FlowContext<RpcHeadMeta> msg) {
        RpcHeadMeta headMeta = msg.headMeta;

        // 添加心跳包处理
        if (headMeta.isHeartbeat()) {
            handleHeartbeat(session, headMeta);
            return;
        }

        if (!headMeta.isRpc() || !headMeta.isRpcResponse()) {
            ActionBus.handlerAction(session.hashCode(), msg);
        } else {
            RpcClient client = RpcSessionManager.getOrCreateClient(session);
            if (client != null) {
                client.handleRpcResponse(msg);
            }
        }
    }

    @Override
    public void stateEvent(AioSession session, StateMachineEnum state, Throwable error) {
        if (state == StateMachineEnum.SESSION_CLOSED) {
            RpcSessionManager.onSessionClosed(session);
        }
    }

    // 新增：心跳处理逻辑
    private void handleHeartbeat(AioSession session, RpcHeadMeta headMeta) {
        if (headMeta.isRpcResponse()) {
            // 心跳请求 - 发送响应
            RpcHeadMeta response = new RpcHeadMeta(
                    (short) headMeta.cmd(),
                    true,
                    true,
                    headMeta.rpcRequestId()
            );
            ByteBuffer buffer = ByteBuffer.allocate(7);
            response.generateHeader(buffer);
            try {
                session.writeBuffer().write(buffer.array());
            } catch (IOException e) {
                throw new RpcException("Rpc心跳发不出去！");
            }
        }
    }
}